class Task < ActiveRecord::Base
  belongs_to :project
  belongs_to :user # responsible of the task
  belongs_to :creator, :class_name=>"User", :foreign_key=>'created_by' # creator of the task
  belongs_to :task # so we can have tasks dependant of others
  has_many :notes, :dependent => :destroy
  has_many :tasks, :dependent => :destroy

  acts_as_taggable
  acts_as_tree :foreign_key=>'task_id' # TODO: use :counter_cache=>true

  #validates_presence_of :project_id, :title, :on=>:update

  def has_subtasks
    subtasks_count > 0
  end
  
  def subtasks_count
    tasks.select{|t| t.done == 0}.size
  end

  def undo
    self.done_on  = nil
    self.done = 0
    task.undo! if task # recursive
  end
  
  def undo!
    undo
    save
  end
  
  def self.inbox_tasks(user)
    Task.find(:all,:conditions=>"user_id=#{user.id} and done=0 and project_id=0")
  end
  
  def set_remains(orig_est, cur_est, elapsed)
    self.orig_est    = orig_est if(orig_est!='')
    if cur_est != ''
      self.cur_est     = cur_est
      self.orig_est    = cur_est if self.orig_est == nil
    elsif orig_est != ''
      self.cur_est = orig_est
    else
      self.cur_est = nil
    end
    self.elapsed     = elapsed if elapsed != ''
    if self.cur_est and self.elapsed
      diff     = self.cur_est - self.elapsed
      if diff >=0
        self.remains = diff
      else
        self.cur_est =  self.elapsed
        self.remains = 0
      end
    else
      self.remains = self.cur_est
    end
    self.remains = 0 if self.remains == nil
  end
  
  def compute_remains # compute subremains field and propagate to parents
    self.subremains = tasks.inject(0.0) { |sum,t| (t.done==1 ? sum : (sum + t.subremains.to_f))} + self.remains.to_f
    #puts "#{title} sum: #{subremains}"
    save
    task.compute_remains if task
  end
 
end

